"""
API蓝图
"""
from flask import Blueprint, jsonify, request, render_template
from flask_login import login_required, current_user
from app.services import ProjectService
from app.models import import_models
from app import db

# 导入模型
models = import_models()
User = models['User']

# 创建API蓝图
api_bp = Blueprint('api', __name__, url_prefix='/api')

@api_bp.route('/projects/<int:project_id>/tasks')
@login_required
def get_project_tasks(project_id):
    """获取项目任务列表API"""
    # 获取页码参数，默认为1
    page = request.args.get('page', 1, type=int)
    per_page = 10  # 每页显示10条记录
    
    # 获取项目任务分页数据
    tasks_pagination = ProjectService.get_project_tasks_paginated(
        project_id, current_user.id, page=page, per_page=per_page)
    
    if not tasks_pagination:
        return jsonify({'error': '无权限访问此项目或项目不存在'}), 403
    
    # 渲染任务列表HTML
    return render_template('partials/tasks_list.html', 
                          tasks=tasks_pagination.items, 
                          tasks_pagination=tasks_pagination,
                          project_id=project_id)

@api_bp.route('/users/<int:user_id>/status', methods=['POST'])
@login_required
def update_user_status(user_id):
    """更新用户状态API"""
    # 检查权限，只有管理员可以修改用户状态
    if current_user.role != 'admin':
        return jsonify({'error': '没有权限执行此操作'}), 403
    
    # 获取用户
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    
    # 防止管理员修改自己的状态
    if user.id == current_user.id:
        return jsonify({'error': '不能修改自己的状态'}), 403
    
    # 获取新状态
    data = request.get_json()
    if not data or 'status' not in data:
        return jsonify({'error': '缺少状态参数'}), 400
    
    new_status = data['status']
    valid_statuses = ['在职', '离职', '休假']
    
    if new_status not in valid_statuses:
        return jsonify({'error': '无效的状态值'}), 400
    
    # 更新用户状态
    user.status = new_status
    db.session.commit()
    
    return jsonify({'success': True, 'message': f'用户状态已更新为: {new_status}'})